package com.yk.filedownload.combiner;

import com.yk.filedownload.ConfigIt.Configuration;
import com.yk.filedownload.entity.DataCarrier;
import org.json.JSONObject;
import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Project Name:cykfiledownload
 * File Name:CombinerProducer
 * Package Name:com.yk.filedownload.combiner
 * Date:2017\12\14 0014
 * Author:dengtianjia
 * Description:
 * Copyright (c) 2017, 重庆云凯科技有限公司 All Rights Reserved.
 */
public class CombinerProducer {

    /**
     * 组装线程池
     */
    private static ExecutorService threadPool = Executors.newFixedThreadPool(Configuration.COMBIN_MAX_THREAD_NUM);


    /**
     * 组装文件
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception{

        String header = "{\"PackNum\":19,\"FileInfo\":\"\",\"FileType\":\"msi\",\"FileId\":\"92e540f9-393d-4e5f-b978-96b40fa995e6\",\"FileSize\":189680640}\n";
        JSONObject json = new JSONObject(header);
        String[] addrs = new String[json.getInt("PackNum")];
        String metaPath = "H:/test/file/";
        for(int i=0;i<json.getInt("PackNum");i++){
            addrs[i] = metaPath+json.getString("FileId")+"@"+i+".temp";
        }
        String outFile = metaPath + json.getString("FileId") +"."+json.getString("FileType");
        DataCarrier carrier = new DataCarrier();
        /**
         * 初始化文件
         */
        RandomAccessFile randomAccessFile = new RandomAccessFile(outFile,"rw");
        for(int i = 0 ; i < addrs.length ; i++){
            try {
                File temp_file = new File(addrs[i]);
                byte[] buffer = null;
                FileInputStream fis = new FileInputStream(temp_file);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] b = new byte[1024];
                int n ;
                while ((n= fis.read(b))!=-1){
                    bos.write(b,0,n);
                }
                fis.close();
                bos.close();
                buffer = bos.toByteArray();
                carrier.setCompressData(buffer);
                System.out.println(carrier.UncompressData().length);
                randomAccessFile.seek(Configuration.MUIL_FILEDOWNLOAD_THRESHOLD*i);
                randomAccessFile.write(carrier.UncompressData());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        randomAccessFile.close();
    }


}
